using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
using Cyys.Inventory;

public class Player : MonoBehaviour
{
    public PlayerDetails playerDetail;

    //角色是否生成完毕
    private bool createPlayerFinish;
    // 移动
    [HideInInspector] public Vector2 inputDirection;
    private float currentSpeed;

    // 路径跟随相关变量
    private bool isFollowingPath = false;
    private List<Vector3Int> pathToFollow;
    private int currentPathIndex = 0;
    private Tilemap pathTilemap;
    public const float ReachedThreshold = 0.1f;

    private IState currentState;
    private Dictionary<PlayerStateType, IState> states = new Dictionary<PlayerStateType, IState>();

    [HideInInspector] public Rigidbody2D rb;
    [HideInInspector] public Animator animator;
    [HideInInspector] public SpriteRenderer sr;

    private void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        animator = GetComponent<Animator>();
        sr = GetComponent<SpriteRenderer>();
        createPlayerFinish = false;

        // 初始化状态机
        states.Add(PlayerStateType.Idle, new PlayerIdleState(this));
        states.Add(PlayerStateType.Move, new PlayerMoveState(this));
        states.Add(PlayerStateType.PathFollow, new PlayerPathFollowState(this));
    }

    private void Update()
    {
        currentState?.OnUpdate();
    }
    private void FixedUpdate()
    {
        currentState?.OnFixedUpdate();
    }



    private void OnEnable()
    {
        EventHandler.AfterSceneLoadEvent += OnAfterSceneLoadEvent;
        EventHandler.CharacterChanged += OnCharacterChanged;
        EventHandler.MoveEvent += OnMoveEvent;
        EventHandler.StopMoveEvent += OnStopMoveEvent;
        EventHandler.StartFollowingPath += OnStartFollowingPath;
    }

    private void OnDisable()
    {
        EventHandler.AfterSceneLoadEvent -= OnAfterSceneLoadEvent;
        EventHandler.CharacterChanged -= OnCharacterChanged;
        EventHandler.MoveEvent -= OnMoveEvent;
        EventHandler.StopMoveEvent -= OnStopMoveEvent;
        EventHandler.StartFollowingPath -= OnStartFollowingPath;
    }

    private void OnAfterSceneLoadEvent()
    {
        //为地图上的角色赋值
        
    }

    // 应用角色配置
    public void OnCharacterChanged(PlayerDetails config)
    {
        
        if (config == null) return;

        playerDetail = config;

        TransitionState(PlayerStateType.Idle);
        playerDetail.input.EnablePlayerInput();

        if (animator != null)
        {
            animator.runtimeAnimatorController = config.animatorController;
        }

        if (sr != null && config.defaultSprite != null)
        {
            sr.sprite = config.defaultSprite;
        }
        createPlayerFinish = true;
    }

    private void OnMoveEvent(Vector2 moveInput) => inputDirection = moveInput;
    private void OnStopMoveEvent() => inputDirection = Vector2.zero;




    // 开始跟随路径
    public void OnStartFollowingPath(List<Vector3Int> path, Tilemap tilemap)
    {
        if (path == null || path.Count == 0) return;

        pathToFollow = path;
        pathTilemap = tilemap;
        currentPathIndex = 0;
        isFollowingPath = true;

        StartCoroutine(StartFollowingPath());
    }

    private IEnumerator StartFollowingPath()
    {
        if (createPlayerFinish)
        {
            transform.position = pathTilemap.GetCellCenterWorld(pathToFollow[0]);
            playerDetail.input.DisableAllInputs();
            TransitionState(PlayerStateType.PathFollow);
        }
        yield return createPlayerFinish;
    }

    // 路径数据访问
    public bool IsFollowingPath => isFollowingPath;
    public Vector3Int? CurrentTargetCell =>
        (pathToFollow != null && currentPathIndex < pathToFollow.Count) ?
        pathToFollow[currentPathIndex] : (Vector3Int?)null;
    public Tilemap PathTilemap => pathTilemap;

    // 路径点更新
    public void AdvanceToNextPathPoint()
    {
        if (pathToFollow == null) return;

        currentPathIndex++;

        if (currentPathIndex >= pathToFollow.Count)
        {
            if (playerDetail.loopPath) {
                currentPathIndex = 0;
                // 触发循环计数
                if (LoopManager.Instance != null)
                    LoopManager.Instance.AddLoop();
            }
            else StopFollowingPath();
        }
    }

    // 停止路径跟随
    public void StopFollowingPath()
    {
        if (!isFollowingPath) return;

        isFollowingPath = false;
        rb.velocity = Vector2.zero;
        pathToFollow = null;
        pathTilemap = null;
        currentPathIndex = 0;

        playerDetail.input.EnablePlayerInput();
        TransitionState(PlayerStateType.Idle);
    }


    public void Move()
    {
        currentSpeed = playerDetail.normalSpeed;
        rb.velocity = inputDirection * currentSpeed;
        UpdateFacingDirection();
    }

    // 更新角色朝向
    public void UpdateFacingDirection()
    {
        if (Mathf.Abs(inputDirection.x) > 0.1f)
        {
            sr.flipX = inputDirection.x < 0;
        }
    }

    // 路径移动方法
    public void MoveAlongPath(Vector2 direction)
    {
        float pathSpeed = playerDetail.pathFollowSpeed;
        rb.velocity = direction * pathSpeed;
        UpdatePathFacingDirection(direction);
    }

    private void UpdatePathFacingDirection(Vector2 direction)
    {
        if (Mathf.Abs(direction.x) > 0.1f)
        {
            sr.flipX = direction.x < 0;
        }
    }

    // 状态切换
    public void TransitionState(PlayerStateType type)
    {
        currentState?.OnExit();
        if (states.TryGetValue(type, out var newState))
        {
            currentState = newState;
            currentState.OnEnter();
        }
    }

}
